/*
 * 文 件 名 : RequestUtils.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-30
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.web;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.fire8.dolphin.db.FriendDAO;
import com.fire8.dolphin.model.Answer;
import com.fire8.dolphin.model.Question;
import com.fire8.dolphin.model.UserInfo;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;

/**
 * 请求远程数据工具类
 * 
 *
 * @author  lixg
 * @version [版本号,2012-8-30]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class RequestUtils
{
    final static String TAG = "dolphin";
    public static final String URL=DolphinApplication.URL;
    public static final String IMG_URL=URL+"upload/pic/";
    
    private static RequestUtils request;
    
    private static HttpClient client;
    //static StringBuffer url = new StringBuffer(URL);
    public RequestUtils(){}
    public static RequestUtils getInstall()
    {
        if(request == null)
        {
            request = new RequestUtils();
            
        }
        return request;
    }
    
    private HttpClient getHttpClient()
    {
        if(client == null)
        {
            BasicHttpParams params = new BasicHttpParams();
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
            schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
            client =  new DefaultHttpClient(cm, params);
        }
        return client;
    }
    /**
     * 请求远程服务
     * <功能详细描述>
     * @param url
     * @param param
     * @return [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    public  String getHttpJson(String url, JSONObject param)
    {
        
        
        String retSrc = null;
        HttpPost request = new HttpPost(url);
        
        try
        {
            // 绑定到请求 Entry 
            StringEntity se = new StringEntity(param.toString(),HTTP.UTF_8);
            request.setEntity(se);
            // 发送请求 
            HttpResponse httpResponse = getHttpClient().execute(request);
            // 得到应答的字符串，这也是一个 JSON 格式保存的数据 
            retSrc = EntityUtils.toString(httpResponse.getEntity());
        }
        catch (Exception e)
        {
            Log.e(TAG, "请求远程数据异常", e);
        }
        
        return retSrc;
    }
    /**
     * 请求远程服务
     * <功能详细描述>
     * @param url
     * @param param
     * @return [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    public  String getHttpJson(String url, List<NameValuePair> param)
    {
        String retSrc = null;
        HttpPost request = new HttpPost(url);
        try
        {
            // 绑定到请求 Entry 
            request.setEntity(new UrlEncodedFormEntity(param,HTTP.UTF_8));
            // 发送请求 
            HttpResponse httpResponse = getHttpClient().execute(request);
            // 得到应答的字符串，这也是一个 JSON 格式保存的数据 
            retSrc = EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8);
        }
        catch (Exception e)
        {
            Log.e(TAG, "请求远程数据异常", e);
        }
        
        return retSrc;
    }
    /**
     * 请求远程服务
     * <功能详细描述>
     * @param url
     * @param param
     * @return [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    public  String getHttpJson(String url, String json)
    {
        String retSrc = null;
        HttpPost request = new HttpPost(url);
        try
        {
            // 绑定到请求 Entry 
            StringEntity se = new StringEntity(json);
            request.setEntity(se);
            request.setHeader("json", "application/json");
            request.setHeader(HTTP.CONTENT_TYPE, "application/json");
            // 发送请求 
            HttpResponse httpResponse = new DefaultHttpClient().execute(request);
            // 得到应答的字符串，这也是一个 JSON 格式保存的数据 
            retSrc = EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8);
        }
        catch (Exception e)
        {
            Log.e(TAG, "请求远程数据异常", e);
        }
        
        return retSrc;
    }
    
    public  boolean isConnect(Context context)
    {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理） 
        try
        {
            ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null)
            {
                // 获取网络连接管理的对象 
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected())
                {
                    // 判断当前网络是否已经连接 
                    if (info.getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogUtil.e("当前网络不可用",e);
        }
        return false;
    }
    
    public   List<Question> getQuestionList(Integer value,Integer operation,String userId,String orderby)
    {
        return getQuestionList(value,operation,userId,orderby,null);
    }
    /**
     * 取问题列表
     * 
     * @param remoteId 当前最大或最小的ID
     * @param operation 向上或是向下，取当前ID之前的或之后的数据[1：向上(>remoteId)；0：向下]
     * @param userId [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    public   List<Question> getQuestionList(Integer value,Integer operation,String userId,String orderby,String recType)
    {
        
        List<Question> list = new ArrayList<Question>();
        //JSONObject param = new JSONObject();
        try
        {
            
            List<NameValuePair> param = new ArrayList<NameValuePair>();
            param.add(new BasicNameValuePair("recordNum",value==null?null:String.valueOf(value)));
            param.add(new BasicNameValuePair("operation",operation==null?null:String.valueOf(operation)));
            param.add(new BasicNameValuePair("userId",userId));
            param.add(new BasicNameValuePair("orderby",orderby));
            param.add(new BasicNameValuePair("recType",recType));
            String json = RequestUtils.getInstall().getHttpJson(URL+"question/getQuestionList.php", param);
            //String json="{\"time\":\"\",\"desc\":\"\",\"msgCode\":\"1\",\"serverCode\":\"\",\"msgId\":\"\",\"msgBody\":[{\"queryType\":0,\"title\":\"a3\",\"questionId\":3,\"userId\":2,\"context\":\"b3\",\"pageSize\":0,\"beginTime\":\"\",\"endTime\":\"\",\"userInfo\":null,\"updateDate\":\"2012-08-22 15:20:00\"},{\"queryType\":0,\"title\":\"a2\",\"questionId\":2,\"userId\":2,\"context\":\"b2\",\"pageSize\":0,\"beginTime\":\"\",\"endTime\":\"\",\"userInfo\":null,\"updateDate\":\"2012-08-22 15:20:00\"},{\"queryType\":0,\"title\":\"aa\",\"questionId\":1,\"userId\":1,\"context\":\"bb\",\"pageSize\":0,\"beginTime\":\"\",\"endTime\":\"\",\"userInfo\":null,\"updateDate\":\"2012-08-21 12:30:00\"}]}";
            if(StringUtil.isEmpty(json))
            {
                return list;
            }
            LogUtil.d(json);
            JSONObject data = new JSONObject(json);
            String msgCode = data.getString("msgCode");
            String desc = data.getString("desc");
            if("1".equals(msgCode))
            {
                JSONArray jsonArray = data.getJSONArray("msgBody");
                int len = jsonArray.length();
                for (int i = 0; i < len; i++)
                {
                    
                    JSONObject object = jsonArray.getJSONObject(i);
                    
                    String account = object.getString("account");
                    String userName = object.getString("userName");
                    
                    Question q = new Question();
                    q.setTitle(object.getString("title"));
                    q.setRemoteId(object.getString("questionId"));
                    q.setUserId(object.getString("userId"));
                    q.setContext(object.getString("context"));
                    q.setUpdateDate(object.getString("updateDate"));
                    q.setUserName(userName==null?account:userName);
                    q.setUserHead(object.getString("headPic"));
                    q.setAnswerNum(object.getString("answerNum"));
                    q.setPicture(object.getString("picture"));
                    q.setVoice(object.getString("voice"));
                    q.setVoiceLong(object.getInt("voiceLong"));
                    list.add(q);
                    //Log.d(TAG, "questionId="+questionId);
                }
            }else
            {
                Log.e(TAG, desc);
            }
        }
        catch (Exception e)
        {
            Log.e(TAG, "" ,e);
        }
        return list;
    }
    
    public  List<Answer> getAnswer(String questionId)
    {
        List<Answer> list = new ArrayList<Answer>();
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        try
        {
            
            param.add(new BasicNameValuePair("questionId",questionId));            
            String json = RequestUtils.getInstall().getHttpJson(URL+"answer/getAnswerList.php", param);
            if(StringUtil.isEmpty(json))
            {
                return null;
            }
            LogUtil.d(json);
            JSONObject data = new JSONObject(json);
            String msgCode = data.getString("msgCode");
            String desc = data.getString("desc");
            if("1".equals(msgCode))
            {
                JSONArray jsonArray = data.getJSONArray("msgBody");
                int len = jsonArray.length();
                for (int i = 0; i < len; i++)
                {
                    Answer answer = new Answer();
                    JSONObject object = jsonArray.getJSONObject(i);
                    String answerId = object.getString("answerId");
                    String answerType = object.getString("answerType");
                    String context = object.getString("context");
                    String updateDate = object.getString("updateDate");
                    String uId = object.getString("userId");
                    if(!object.isNull("userInfo"))
                    {
                        JSONObject userinfo = object.getJSONObject("userInfo");
                        answer.setUserName(userinfo.getString("userName"));
                        answer.setUserHead(userinfo.getString("headPic"));
                    }
                    
                    answer.setRemoteId(answerId);
                    answer.setqRemoteId(questionId);
                    answer.setVoice(object.getString("voice"));
                    answer.setaType(answerType);
                    answer.setaContext(context);
                    answer.setUpdateDate(updateDate);
                    answer.setUserId(uId);
                    answer.setVoiceLong(object.getLong("voiceLong"));
                    list.add(answer);
                }
            }else
            {
                Log.e(TAG, desc);
            }
        }
        catch (JSONException e)
        {
            Log.e(TAG, "" ,e);
        }
        return list;
    }
    
    public String multPartURL(String fileName,NameValuePair[] params)
    {
        return multPartURL(new File(fileName),params);
    }
    public String multPartURL(File file,NameValuePair[] params)
    {
        String fileName = null;
        String targetURL = URL+"comm/uploadFile.php";// 上传指定URL
        PostMethod post = new PostMethod(targetURL);
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        try {
            
            Part[] parts=null;
            if(params==null){
                parts=new Part[1];
            }else{
                parts=new Part[params.length+1];
            }
            if (params != null ) {
                int i=0;
                for (NameValuePair entry : params) {
                    parts[i++]=new StringPart( entry.getName(),(String)entry.getValue());
                }
            }
            FilePart filePart=new FilePart("file",file.getName(), file,new FileType().getMIMEType(file),"UTF-8");
            filePart.setTransferEncoding("binary");
            parts[parts.length-1]= filePart;

            post.setRequestEntity( new MultipartRequestEntity(parts, post.getParams()) );
             List<Header> headers = new ArrayList<Header>();

            client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
            int status = client.executeMethod(post);
            if (status == HttpStatus.SC_OK)
            {
                
                LogUtil.d("上传成功");
                LogUtil.d("返回的内容:"+post.getResponseBodyAsString());
                String json = post.getResponseBodyAsString();
                JSONObject data = new JSONObject(json);
                String msgCode = data.getString("msgCode");
                if("1".equals(msgCode))
                {
                    fileName = data.getString("msgBody");
                }
            }
            else
            {
                LogUtil.d("上传失败");
            }
        } catch (Exception ex) {
            Log.e(TAG, "上传文件异常", ex);
        } finally {
            post.releaseConnection();
            client=null;
        }
        return fileName;
    }
    
    /**
     * 同步用户好友
     * <功能详细描述>
     * @param param 传进来的是好友的account
     * @param friendDao [参数说明]
     *
     * @author lixg
     * @see [类、类#方法、类#成员]
     */
    public  void findFriendList(List<NameValuePair> param,FriendDAO friendDao)
    {
        try
        {
            //同步好友
            String json = RequestUtils.getInstall().getHttpJson(URL+"user/findFriendList.php", param);
            if(!StringUtil.isEmpty(json))
            {
                JSONObject data = new JSONObject(json);
                String msgCode = data.getString("msgCode");
                //String desc = data.getString("desc");
                if("1".equals(msgCode))
                {
                    JSONArray array = data.getJSONArray("msgBody");
                    int len = array.length();
                    for (int i = 0; i < len; i++)
                    {
                        JSONObject obj = array.getJSONObject(i);
                        UserInfo user = new UserInfo();
                        user.setUserId(Integer.valueOf(obj.getString("userId")));
                        user.setUserName(obj.getString("userName"));
                        user.setAccount(obj.getString("account"));
                        user.setHeadPic(obj.getString("headPic"));
                        user.setPoint(Integer.valueOf(obj.getString("point")));
                        user.setRemark(obj.getString("remark"));
                        user.setUserTitle(obj.getString("userTitle"));
                        friendDao.add(user);
                    }
                }
            }
        }
        catch (Exception e)
        {
            LogUtil.e("同步好友失败", e);
            
        }
    }
    
    
    public void checkout()
    {
        
    }
    
    public boolean uploadFileClient(String file)
    {
        boolean result=false;
        String targetURL = URL+"comment/uploadFile.php";// 上传指定URL
        File targetFile = new File(file);// 指定上传文件
        PostMethod filePost = new PostMethod(targetURL);
        try
        {
            // 通过以下方法可以模拟页面参数提交
            //byte[] buffer = new byte[1024];
            Part[] parts ={new FilePart(targetFile.getName() + System.currentTimeMillis(),targetFile)};
            filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
            org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
            client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
            int status = client.executeMethod(filePost);
            if (status == HttpStatus.SC_OK)
            {
                result = true;
                LogUtil.d("上传成功");
                LogUtil.d("返回的内容:"+filePost.getResponseBodyAsString());
            }
            else
            {
                LogUtil.d("上传失败");
            }
        }
        catch (Exception ex)
        {
            LogUtil.e("",ex);
        }
        finally
        {
            filePost.releaseConnection();
        }
        return result;
    }

}
